function deepCopy<T>(obj: T): T {
    if (obj === null || obj === undefined) {
        return obj as any;
    }
    const visited = new WeakMap<any, any>();

    function copy(src: any): any {
        if (visited.has(src)) {
            return visited.get(src);
        }

        let target: any;

        if (Array.isArray(src)) {
            target = [];
            src.forEach((item, index) => {
                target[index] = copy(item);
            });
        } else if (src instanceof Date) {
            target = new Date(src);
        } else if (src instanceof RegExp) {
            // 注意：RegExp的flags属性在ES6中引入  
            const flags = (src.flags || '').replace(/['"]/g, '');
            target = new RegExp(src.source, flags);
        } else if (typeof src === 'object' && src !== null) {
            target = {};
            Object.keys(src).forEach(key => {
                target[key] = copy(src[key]);
            });
        } else {
            target = src;
        }

        visited.set(src, target);

        return target;
    }

    return copy(obj) as T;
}

export default deepCopy;